给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
进阶:你能尝试使用一趟扫描实现吗?
示例 1:
输入:head = [1,2,3,4,5], n = 2 输出:[1,2,3,5] 示例 2:
输入:head = [1], n = 1 输出:[] 示例 3:
输入:head = [1,2], n = 1 输出:[1]
法一: 快慢指针
var removeNthFromEnd = function (head, n) {
let dummyHead = new ListNode(0, head);
let slow = dummyHead;
let fast = dummyHead;
while (n-- && fast) {
fast = fast.next
}
fast = fast.next; // fast再提前走一步,因为需要让slow指向删除节点的上一个节点
while (fast) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next
return dummyHead.next;
};
法二: 先遍历得到正序是第几个元素移除,再次遍历移除太严肃
var removeNthFromEnd = function (head, n) {
let dummyHead = new ListNode(0, head);
let cur1 = dummyHead;
let cur = dummyHead;
let num1 = 0;
let num = 0;
while (cur1) {
cur1 = cur1.next
num1++;
}
while (cur) {
if (num === num1 - n -1) {
cur.next = cur.next.next
console.log(num)
} else {
cur = cur.next
}
num++;
}
console.log(cur1, cur, dummyHead)
return dummyHead.next;
};